from flask import Blueprint, request, current_app
from flask_json import as_json
from flask_jwt_extended import jwt_required

from .is_staff_user import is_staff_user
from app import db
from app.models import CommonResult, CommonPage, Category, Article
from app.auth.auth_decorator import has_role
from app.common.enums import RoleCodeEnum

log = current_app.logger
admin_category = Blueprint('admin_category', __name__, url_prefix='/admin/category')


# 注册蓝图
def register_controller(app):
    app.register_blueprint(admin_category)


# 分页查询
@admin_category.post('/page')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def page():
    data = request.get_json()
    current = 1
    page_size = 10
    page_obj = Category.query
    if data:
        current = data.get('current') or 1
        page_size = data.get('page_size') or 10
        name = data.get('name')
        if name and name.strip():
            page_obj = page_obj.filter(Category.name.like('%{keyword}%'.format(keyword=name)))
    # 分页查询
    page_data = page_obj.paginate(
        page=current,
        per_page=page_size,
        error_out=False
    )
    return CommonResult(data=CommonPage(page_data))


# 获取详情
@admin_category.get('/get/<int:category_id>')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def info(category_id):
    category = Category.query.get(category_id)
    if category is None:
        return CommonResult(code=500, msg='记录不存在')
    return CommonResult(data=category, msg='获取成功')


# 添加记录
@admin_category.post('/add')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def add():
    data = request.get_json()
    if data and (data.get('name') is None or not data.get('name').strip()):
        return CommonResult(code=500, msg='请输入分类名称')
    # 填充数据
    record = Category()
    record.__dict__.update(data)
    # 保存数据库
    db.session.add(record)
    db.session.commit()
    return CommonResult(data=data, msg='保存成功')


# 修改信息
@admin_category.post('/update')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def update():
    data = request.get_json()
    # 查询被修改的记录
    category_id = int(data.get('id'))
    record = Category.query.get(category_id)
    if record is None:
        return CommonResult(code=500, msg='记录不存在')
    # 更新用户信息
    db.session.query(Category).filter(Category.id == category_id).update(data)
    db.session.commit()
    return CommonResult(data=record, msg='修改成功')


# 删除记录
@admin_category.get('/delete/<int:category_id>')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def delete(category_id):
    # 判断分类是否存在
    record = Category.query.get(category_id)
    if record is None:
        return CommonResult(code=500, msg='删除的记录不存在')
    # 设置关联为文章的null
    db.session.query(Article).filter(Article.category_id == category_id).update({'category_id': None})
    # 删除记录
    db.session.delete(record)
    db.session.commit()
    return CommonResult(msg='删除成功')
